/*
*	Upload files to the server using HTML 5 Drag and drop the folders on your local computer
*
*	Tested on:
*	Mozilla Firefox 3.6.12
*	Google Chrome 7.0.517.41
*	Safari 5.0.2
*	Safari na iPad
*	WebKit r70732
*
*	The current version does not work on:
*	Opera 10.63 
*	Opera 11 alpha
*	IE 6+
*/

function uploader(place, status, targetPHP, show) {

	
	// Upload image files
	upload = function(file) {
	
		// Firefox 3.6, Chrome 6, WebKit
		if(window.FileReader) { 
				
			// Once the process of reading file
			this.loadEnd = function() {
				error = 0;
				var myindex  = document.getElementById('account').selectedIndex;
        if(myindex == 0){
        $('#select_box_account').css("border-radius","1px");
        $('#select_box_account').css("-moz-box-shadow","0px 0px 10px red");
        $('#select_box_account').css("-webkit-box-shadow","0px 0px 10px red");
        $('#select_box_account').css("box-shadow","0px 0px 10px red");
        error = 1;
        } 
    		var account = document.getElementById('account').options[myindex].value;
        myindex  = document.getElementById('importClass').selectedIndex;
        if(myindex == 0){
        $('#selectBox_importClass').css("border-radius","1px");
        $('#selectBox_importClass').css("-moz-box-shadow","0px 0px 10px red");
        $('#selectBox_importClass').css("-webkit-box-shadow","0px 0px 10px red");
        $('#selectBox_importClass').css("box-shadow","0px 0px 10px red");
        error = 1;
        } 
        if(error != 0){
        exit();
        }
        $('#select_box_account').css("border-radius","");
              $('#select_box_account').css("-moz-box-shadow","");
              $('#select_box_account').css("-webkit-box-shadow","");
              $('#select_box_account').css("box-shadow","");
              $('#selectBox_importClass').css("border-radius","");
              $('#selectBox_importClass').css("-moz-box-shadow","");
              $('#selectBox_importClass').css("-webkit-box-shadow","");
              $('#selectBox_importClass').css("box-shadow","");
    		var importClass = document.getElementById('importClass').options[myindex].value;
        
				bin = reader.result;				
				xhr = new XMLHttpRequest();
				xhr.open('POST', targetPHP+'?up=true&account='+account+'&importclass='+importClass, true);
				var boundary = 'xxxxxxxxx';
	 			var body = '--' + boundary + "\r\n";  
				body += "Content-Disposition: form-data; name='upload'; filename='" + file.name + "'\r\n";  
				body += "Content-Type: application/octet-stream\r\n\r\n";  
				body += bin + "\r\n";  
				body += '--' + boundary + '--';      
				xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
				// Firefox 3.6 provides a feature sendAsBinary ()
				xhr.onreadystatechange = handleRequestStateChange;
				if(xhr.sendAsBinary != null) { 
        document.getElementById(status).innerHTML = "<img src='ajax-loader.gif' alt='Loading' class='loader'/>";
					xhr.sendAsBinary(body); 
				// Chrome 7 sends data but you must use the base64_decode on the PHP side
				} else { 
        document.getElementById(place).innerHTML = "<img src='ajax-loader.gif' alt='Loading' class='loader'/>";
					xhr.open('POST', targetPHP+'?up=true&base64=true&account='+account+'&importclass='+importClass, true);
					xhr.setRequestHeader('UP-FILENAME', file.name);
					xhr.setRequestHeader('UP-SIZE', file.size);
					xhr.setRequestHeader('UP-TYPE', file.type);
					xhr.send(window.btoa(bin))
				}
				function handleRequestStateChange() 
				{          
               
				    
				  // continue if the process is completed
				  if (xhr.readyState == 4) 
				  {
					// continue only if HTTP status is "OK"
					if (xhr.status == 200) 
					{
					  // retrieve the response
					  
					  document.getElementById('list1').innerHTML = xhr.responseText ;
            if (status) {
  					  document.getElementById(status).innerHTML = 'Loaded : 100% Next file ...';
              document.getElementById(place).innerHTML = "";
				    }  
					  
					
					 
					  // do something with the response
					  // ...
					  // ...
					}
				  } 
				}

				if (show) {
					var newFile  = document.createElement('div');
					newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B';
					document.getElementById(show).appendChild(newFile);				
				}
				
			}
				
			// Loading errors
			this.loadError = function(event) {
				switch(event.target.error.code) {
					case event.target.error.NOT_FOUND_ERR:
						document.getElementById(status).innerHTML = 'File not found!';
					break;
					case event.target.error.NOT_READABLE_ERR:
						document.getElementById(status).innerHTML = 'File not readable!';
					break;
					case event.target.error.ABORT_ERR:
					break; 
					default:
						document.getElementById(status).innerHTML = 'Read error.';
				}	
			}
		
			// Reading Progress
			this.loadProgress = function(event) {
				if (event.lengthComputable) {
					var percentage = Math.round((event.loaded * 100) / event.total);
					document.getElementById(status).innerHTML = 'Loaded : '+percentage+'%';
				}				
			}
				
			// Preview images
			this.previewNow = function(event) {		
				bin = preview.result;
				var img = document.createElement("img"); 
				img.className = 'addedIMG';
			    img.file = file;   
			    img.src = bin;
				document.getElementById(show).appendChild(img);
			}

		reader = new FileReader();
		// Firefox 3.6, WebKit
		if(reader.addEventListener) { 
			reader.addEventListener('loadend', this.loadEnd, false);
			if (status != null) 
			{
				reader.addEventListener('error', this.loadError, false);
				reader.addEventListener('progress', this.loadProgress, false);
			}
		
		// Chrome 7
		} else { 
			reader.onloadend = this.loadEnd;
			if (status != null) 
			{
				reader.onerror = this.loadError;
				reader.onprogress = this.loadProgress;
			}
		}
		var preview = new FileReader();
		// Firefox 3.6, WebKit
		if(preview.addEventListener) { 
			preview.addEventListener('loadend', this.previewNow, false);
		// Chrome 7	
		} else { 
			preview.onloadend = this.previewNow;
		}
		
		// The function that starts reading the file as a binary string
     	reader.readAsBinaryString(file);
	     
    	// Preview uploaded files
    	if (show) {
	     	preview.readAsDataURL(file);
	 	}
		
  		// Safari 5 does not support FileReader
		} else {
			xhr = new XMLHttpRequest();
			xhr.open('POST', targetPHP+'?up=true', true);
			xhr.setRequestHeader('UP-FILENAME', file.name);
			xhr.setRequestHeader('UP-SIZE', file.size);
			xhr.setRequestHeader('UP-TYPE', file.type);
			xhr.send(file); 
			
			if (status) {
				document.getElementById(status).innerHTML = 'Loaded : 100%';
			}
			if (show) {
				var newFile  = document.createElement('div');
				newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B';
				document.getElementById(show).appendChild(newFile);
			}	
		}				
	}

	// Function drop file
	this.drop = function(event) {
		event.preventDefault();
	 	var dt = event.dataTransfer;
	 	var files = dt.files;
	 	for (var i = 0; i<files.length; i++) {
			var file = files[i];
			upload(file);
	 	}
	}
	
	// The inclusion of the event listeners (DragOver and drop)

	this.uploadPlace =  document.getElementById(place);
	this.uploadPlace.addEventListener("dragover", function(event) {
		event.stopPropagation(); 
		event.preventDefault();
	}, true);
	this.uploadPlace.addEventListener("drop", this.drop, false); 

} 


$(document).ready(function(){

	
	// The select element to be replaced:
	var select = $('select.account');

	var selectBoxContainer = $('<div>',{
		width		: select.outerWidth(),
		className	: 'tzSelect',
		html		: '<div class="selectBox" id="select_box_account"></div>'
	});

	var dropDown = $('<ul>',{className:'dropDown'});
	var selectBox = selectBoxContainer.find('.selectBox');
	
	// Looping though the options of the original select element
	
	select.find('option').each(function(i){
		var option = $(this);
		
		if(i==select.attr('selectedIndex')){
			selectBox.html(option.text());
		}
		
		// As of jQuery 1.4.3 we can access HTML5 
		// data attributes with the data() method.
		
		if(option.data('skip')){
			return true;
		}
		
		// Creating a dropdown item according to the
		// data-icon and data-html-text HTML5 attributes:
		
		var li = $('<li>',{
			html:	'<span>'+
					option.text()+'</span>'
		});
				
		li.click(function(){
			
			selectBox.html(option.text());
			dropDown.trigger('hide');
			
			// When a click occurs, we are also reflecting
			// the change on the original select element:
			select.val(option.val());
			
			return false;
		});
		
		dropDown.append(li);
	});
	
	selectBoxContainer.append(dropDown.hide());
	select.hide().after(selectBoxContainer);
	
	// Binding custom show and hide events on the dropDown:
	
	dropDown.bind('show',function(){
		
		if(dropDown.is(':animated')){
			return false;
		}
		
		selectBox.addClass('expanded');
		dropDown.slideDown();
		
	}).bind('hide',function(){
		
		if(dropDown.is(':animated')){
			return false;
		}
		
		selectBox.removeClass('expanded');
		dropDown.slideUp();
		
	}).bind('toggle',function(){
		if(selectBox.hasClass('expanded')){
			dropDown.trigger('hide');
		}
		else dropDown.trigger('show');
	});
	
	selectBox.click(function(){
    if(select1Box.hasClass('expanded')){
			dropDown1.trigger('hide');
		}
		dropDown.trigger('toggle');
		return false;
	});
      
  
	// If we click anywhere on the page, while the
	// dropdown is shown, it is going to be hidden:

  
   $(document).click(function(){
      

        dropDown.trigger('hide');

	});


/////////////////////////////////////////////////////////////////////////////


// The select element to be replaced:
	var select1 = $('select.importClass');

	var select1BoxContainer = $('<div>',{
		width		: select1.outerWidth(),
		className	: 'tzSelect',
		html		: '<div class="selectBox" id="selectBox_importClass"></div>'
	});

	var dropDown1 = $('<ul>',{className:'dropDown'});
	var select1Box = select1BoxContainer.find('.selectBox');
	
	// Looping though the options of the original select element
	
	select1.find('option').each(function(i){
		var option = $(this);
		
		if(i==select1.attr('selectedIndex')){
			select1Box.html(option.text());
		}
		
		// As of jQuery 1.4.3 we can access HTML5 
		// data attributes with the data() method.
		
		if(option.data('skip')){
			return true;
		}
		
		// Creating a dropdown item according to the
		// data-icon and data-html-text HTML5 attributes:
		
		var li = $('<li>',{
			html:	'<span>'+
					option.text()+'</span>'
		});
				
		li.click(function(){
			
			select1Box.html(option.text());
			dropDown1.trigger('hide');
			
			// When a click occurs, we are also reflecting
			// the change on the original select element:
			select1.val(option.val());
			
			return false;
		});
		
		dropDown1.append(li);
	});
	
	select1BoxContainer.append(dropDown1.hide());
	select1.hide().after(select1BoxContainer);
	
	// Binding custom show and hide events on the dropDown:
	
	dropDown1.bind('show',function(){
		
		if(dropDown1.is(':animated')){
			return false;
		}
		
		select1Box.addClass('expanded');
		dropDown1.slideDown();
		
	}).bind('hide',function(){
		
		if(dropDown1.is(':animated')){
			return false;
		}
		
		select1Box.removeClass('expanded');
		dropDown1.slideUp();
		
	}).bind('toggle',function(){
		if(select1Box.hasClass('expanded')){
			dropDown1.trigger('hide');
		}
		else dropDown1.trigger('show');
	});
	
	select1Box.click(function(){
  if(selectBox.hasClass('expanded')){
			dropDown.trigger('hide');
		}
    dropDown1.trigger('toggle');
		return false;
	});
      
  
	// If we click anywhere on the page, while the
	// dropdown is shown, it is going to be hidden:

  
   $(document).click(function(){
     dropDown1.trigger('hide'); 
	});      
  
  })


	